﻿using System;
using System.Globalization;
using System.Web;
using System.Web.Mvc;
using Peresvet.Common.Constants.HTML;
using Peresvet.Common.Constants.Text;

namespace Peresvet.Helpers
{
	public static class MenuHelper
	{
		#region Constants

		private const string DEFAULT_CONTROLLER_NAME = "Home";
		private const string ROUTE_DATA_ACTION_REQUIRED_STRING_NAME = "action";
		private const string ROUTE_DATA_CONTROLLER_REQUIRED_STRING_NAME = "controller";

		private const string ACTIVE_MENU_ELEMENT_CSS_CLASS = "active-page";

		#endregion

		public static MvcHtmlString Menu(this HtmlHelper helper)
		{
			var result = new TagBuilder(TagNames.UNORDERED_LIST);

			var topLevelNodes = SiteMap.RootNode.ChildNodes;

			foreach (SiteMapNode node in topLevelNodes)
			{
				result.InnerHtml += MenuItem(helper, helper.Encode(node.Title), node.Url.Trim(Symbols.SLASH.ToCharArray()), node.Description.Trim(Symbols.SLASH.ToCharArray())).ToString();
			}

			return MvcHtmlString.Create(result.ToString());
		}

		public static MvcHtmlString MenuItem(
			this HtmlHelper htmlHelper,
			string text,
			string action,
			string alternativeAction)
		{
			var newElementAction = new UrlHelper(htmlHelper.ViewContext.RequestContext).Action(action, DEFAULT_CONTROLLER_NAME);
			if (newElementAction == null) return null;
			var anchor = new TagBuilder(TagNames.ANCHOR);
			anchor.Attributes.Add(TagAttributes.HREF, newElementAction.ToString(CultureInfo.InvariantCulture));

			var li = new TagBuilder(TagNames.LIST_ITEM);
			var routeData = htmlHelper.ViewContext.RouteData;
			var currentAction = routeData.GetRequiredString(ROUTE_DATA_ACTION_REQUIRED_STRING_NAME);
			var currentController = routeData.GetRequiredString(ROUTE_DATA_CONTROLLER_REQUIRED_STRING_NAME);
			if ((string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase)
				|| string.Equals(currentAction, alternativeAction, StringComparison.OrdinalIgnoreCase))
				&& string.Equals(currentController, DEFAULT_CONTROLLER_NAME, StringComparison.OrdinalIgnoreCase))
				li.AddCssClass(ACTIVE_MENU_ELEMENT_CSS_CLASS);
			li.SetInnerText(text);
			anchor.InnerHtml = li.ToString();

			return MvcHtmlString.Create(anchor.ToString());
		}
	}
}